<template>
  <div class="toggle-radio">
    <div :class="{ active: activeName == 'week' }" @click="changeRange('week')">近一周</div>
    <div :class="{ active: activeName == 'month' }" @click="changeRange('month')">近一月</div>
    <div :class="{ active: activeName == 'year' }" @click="changeRange('year')">近一年</div>
  </div>
</template>

<script>
import {
  defineComponent,
  ref,
  onBeforeMount,
  onMounted,
  onBeforeUnmount,
  watch
} from "vue";

import { parseTime } from "@/utils";


export default defineComponent({
  name: "ToggleButton",
  props: {
    modelValue: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {

    const activeName = ref('week')
    const changeRange = (val) => {
  
      activeName.value = val
      const days =  val == 'week'? 7: val == 'month'? 31: 366
      const start = new Date();
      const end = new Date(new Date(new Date().toLocaleDateString()).getTime()-1);
      start.setTime(start.getTime() - 3600 * 1000 * 24 * days);
      emit("update:modelValue", [start, end])
    }

    watch(()=> props.modelValue, (value) => {
      const diff = (value[1].getTime() - value[0].getTime()) / 86400000
      let type = 'week'
      switch (parseInt(diff)) {
        case 6:
          type = 'week';
          break;
        case 30:
          type = 'month';
          break;
        case 365:
          type = 'year';
          break;
      }
      activeName.value = type
    })
    
   
    // 时间戳
    const timer = ref(null);
    const time = ref(null);
    const week = ref(null)
    const getTime = () => {
      const today = new Date()
      const weekCn = ['日', '一', '二', '三', '四', '五', '六']
      time.value = parseTime(today, "{y}-{m}-{d} {h}:{i}:{s}");
      week.value = '星期' + weekCn[today.getDay()]
    };
    onBeforeMount(() => {
      clearInterval(timer.value)
      timer.value = null;
    });
    getTime();
    onMounted(() => {
      timer.value = setInterval(() => {
        getTime();
      }, 1000);
    });
    onBeforeUnmount(() => {
      clearInterval(timer.value)
      timer.value = null;
    });
    return {
      activeName,
      changeRange,
      time,
      week
    };
  },
});
</script>

<style lang="scss" scoped>
.time {
  font-size: 1rem;
  color: #BAD2FC;
}

.toggle-radio {
  display: flex;
  padding-top: 40px;
  div {
    width: 80px;
    height: 30px;
    background: rgba(46, 105, 235, 0.21);
    border-radius: 18px;
    border: 1px solid #2E69EB;
    line-height: 28px;
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #FFFFFF;
    text-align: center;
    cursor: pointer;
    &.active,&:hover{
     background-color: #2E69EB; 
    }
    & + div {
      margin-left: 20px;
    }
  }
}
</style>